import React, { useEffect, useState } from "react";
import { Image, Input, View, Picker, Text } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import locationIcon from "@/images/icon_location.png";
import searchIcon from "@/images/icon_search.png";
import scanIcon from "@/images/icon_scan.png";
import { AtIcon } from "taro-ui";
import { getToken } from "@/src/service";

import "taro-ui/dist/style/components/icon.scss";

import QQMapWX from "@/src/assets/libs/qqmap-wx-jssdk.min";
import "./index.scss";

let qqmapsdk = new QQMapWX({ key: "GKMBZ-IOOKD-GZI4L-HQL4N-ZMWAS-4TBKR" });

console.log("qqmapsdk--->>", qqmapsdk);

interface Iprops {
  isShowScan?: boolean;
  value?: string;
  onSearch: (str: string) => void;
  onScan?: (str: string) => void;
  onSelectRegion?: (str: string) => void;
}

const Index: React.FC<Iprops> = (props: Iprops) => {
  const [city, setCity] = useState<string[]>([]);
  const [visible, setVisible] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);

  const onSearch = (e: any) => {
    const value = e.detail.value;
    setVisible(false);
    handleSearchHistory(value);
    setTimeout(()=>{
      props.onSearch(value);
    },100)
  };

  // useEffect(() => {
  //   return () => {
  //     setVisible(false);
  //   };
  // }, []);

  const getLoaction = () => {
    Taro.getLocation({
      success: function (res) {
        var latitude = res.latitude;
        var longitude = res.longitude;
        qqmapsdk.reverseGeocoder({
          location: { latitude: latitude, longitude: longitude },
          success: function (ress) {
            const { ad_info } = ress.result;

            const regions = [ad_info.province, ad_info.city, ad_info.district];
            setCity(regions);
            Taro.setStorageSync("city", regions);
          },
          fail(ress) {
            console.log("fail----->>", ress);
          },
        });
      },
      fail(res) {
        console.log("定位授权失败---------->>", res);
      },
    });
  };

  useDidShow(() => {
    if (Taro.getStorageSync("city")) {
      setCity(Taro.getStorageSync("city"));
    } else {
      getLoaction();
    }
    handleSearchHistory();
  });

  const onSelectRegion = (e) => {
    const value = e.detail.value;
    Taro.setStorageSync("city", value);
    setCity(value);
    if (props.onSelectRegion) {
      props.onSelectRegion(value);
    }
  };

  const onScan = () => {
    Taro.scanCode({
      success: (res) => {
        if (props.onScan) {
          props.onScan(res.result);
        } else {
          const parseUrl = res.result.split("&");
          if (parseUrl[0] === "type=poster") {
            if (getToken().access_token) {
              Taro.navigateTo({
                url: `/pages/goodsDetail/index?poster_id=${
                  parseUrl[1].split("=")[1]
                }`,
              });
            } else {
              console.log(
                'parseUrl[1].split("=")[1]',
                parseUrl[1].split("=")[1]
              );
              const params = {
                redirectUrl: "goodsDetail",
                params: {
                  key: "poster_id",
                  value: parseUrl[1].split("=")[1],
                },
              };

              Taro.navigateTo({
                url: `/pages/loginGuide/index?params=${JSON.stringify(params)}`,
              });
            }
          }
        }
      },
    });
  };

  console.log("city------>>", city);

  const onInputFoucs = () => {
    setVisible(true);
  };

  /**
   * value 搜索的值
   */
  const handleSearchHistory = (value?: string) => {
    const oldRecord = Taro.getStorageSync("history") || [];
    if (value) {
      if (!oldRecord.includes(value.trim())) {
        const newRecord = [...oldRecord, value];
        Taro.setStorageSync("history", newRecord);
        setSearchHistory(newRecord);
      }
    } else {
      setSearchHistory(oldRecord);
    }
  };

  const removeHistory = () => {
    Taro.showModal({
      title: "提示",
      content: "您确认删除搜索记录吗？",
      success(res) {
        if (res.confirm) {
          Taro.setStorageSync("history", []);
          setSearchHistory([]);
        }
      },
    });
  };

  // 根据历史设置搜索框的值
  const onClickHistory = (value) => {
    onSearch({
      detail: {
        value,
      },
    });
  };

  console.log("visible--------------->>>", visible);
  return (
    <View className="search">
      <View className="search-wrapper">
        <View className="search-area">
          {!visible && (
            <Picker
              className="location-warpper"
              mode="region"
              value={city || []}
              onChange={onSelectRegion}
            >
              <View className="location">
                <View className="city">
                  {city && city.length ? city[1] : "未知"}
                </View>
                <Image className="icon" src={locationIcon} />
              </View>
            </Picker>
          )}

          {!visible && <View className="line"></View>}
          <View className="input-wrapper">
            {visible ? (
              <Input
                onConfirm={onSearch}
                confirmType="search"
                value={props.value}

                focus={visible}
                placeholder="请输入城市名"
                className="input-real"
              />
            ) : (
              <View className="input-fake" onClick={onInputFoucs}>
                {props.value ? (
                  <Text className="value">{props.value}</Text>
                ) : (
                  <Text className="placeholder">请输入城市名</Text>
                )}
              </View>
            )}

            <Image className="icon" src={searchIcon} />
          </View>
        </View>
        {props.isShowScan && !visible && (
          <Image className="scan" src={scanIcon} onClick={onScan} />
        )}
        {visible && (
          <View className="cancel" onClick={() => setVisible(false)}>
            取消
          </View>
        )}
      </View>
      <View className="blank"></View>
      <View
        className="search-content"
        style={`visibility:${visible ? "visible" : "hidden"}`}
      >
        {searchHistory.length ? (
          <View className="search-content__header">
            <View className="search-content__header--l">最近搜索</View>
            <View className="search-content__header--r"></View>
          </View>
        ) : null}
        <View className="search-content__body">
          {searchHistory.map((item) => (
            <View
              className="item"
              key={item}
              onClick={() => {
                onClickHistory(item);
              }}
            >
              {item}
            </View>
          ))}
        </View>
        {searchHistory.length ? (
          <View className="search-content__footer" onClick={removeHistory}>
            <AtIcon value="trash" size="16" color="#8A8B8C"></AtIcon>
            清空搜索记录
          </View>
        ) : null}
      </View>
    </View>
  );
};

export default Index;
